#include "unp.h"
#include "recvfrom_msg.h"
using namespace std;

void dg_echo(int fd, struct sockaddr* addr, socklen_t addrlen);

void server()
{
  int fd;
  struct sockaddr_in servaddr,cliaddr;

  fd = socket(AF_INET,SOCK_DGRAM,0);
  memset(&servaddr,0,sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = htons(INADDR_ANY);
  servaddr.sin_port = htons(10086);

  bind(fd,(sockaddr*)&servaddr,sizeof(servaddr));

  dg_echo(fd,(sockaddr*)&cliaddr,sizeof(cliaddr));
}


void dg_echo(int fd, struct sockaddr* addr, socklen_t addrlen)
{
  int				 n;
  int 				 flags;
  const int			 on = 1;
  socklen_t 		 len;
  char 				 msg[4096],str[INET6_ADDRSTRLEN], ifname[IFNAMSIZ];
  struct in_addr     in_zero;
  struct in_pktinfo  pktinfo;

#ifdef  IP_PKTINFO
    if (setsockopt(fd, SOL_IP, IP_PKTINFO, &on, sizeof(on)) < 0)
      exit(-1);
#endif
    bzero(&in_zero, sizeof(struct in_addr));    /* all 0 IPv4 address */

  for(;;)
  {
    len = addrlen;
    flags = 0;
    n = recvfrom_msg(fd,msg,sizeof(msg),&flags,addr,&len, &pktinfo);
    printf("From %s", inet_ntop(AF_INET, &pktinfo.ipi_spec_dst, str, sizeof(str)));
    printf(", to %s", inet_ntop(AF_INET, &pktinfo.ipi_addr, str, sizeof(str)));
    printf(", recv i/f = %s\n",if_indextoname(pktinfo.ipi_ifindex, ifname));
    sendto(fd,msg,n,0,addr,len);
  }
}

int main(int argc, char **argv) {
  server();
  return 0;
}

